{{#if template}}
<template>
  <a-modal :title="title" :visible="visible" @ok="handleOk" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="{{label}}" prop="{{prop}}">
        <a-input v-model="form.{{prop}}" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>
{{/if}}

{{#if script}}
<script>
  import { add, edit } from '@/api/{{name}}'

  const defaultForm = {
    id: undefined,
    {{prop}}: null
  }

  export default {
    props: {
      isAdd: {
        type: Boolean,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
        form: { ...defaultForm },
        rules: {
          '{{prop}}': [
            { required: true, message: 'Please input {{prop}}', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      title: function () {
        return this.isAdd ? '新建' : '修改'
      }
    },
    methods: {
      handleCancel(e) {
        this.resetForm()
      },
      handleOk() {
        this.$refs['form'].validate(this.validate)
      },
      async validate(valid) {
        if (valid) {
          this.confirmLoading = true
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }
      },
      async doAdd() {
        try {
          const res = await add(this.form)
          this.$message.success({ content: '添加成功!', duration: 2 })
          this.resetForm()
          this.$emit('refreshTable')
        } catch (err) {
          this.confirmLoading = false
          console.error(err.message)
        }
      },
      async doEdit() {
        try {
          const res = await edit(this.form)
          this.$message.success({ content: '修改成功!', duration: 2 })
          this.resetForm()
          this.$emit('refreshTable')
        } catch (err) {
          this.confirmLoading = false
          console.error(err.message)
        }
      },
      resetForm() {
        this.visible = false
        this.confirmLoading = false
        this.$refs['form'].resetFields()
        this.form = { ...defaultForm }
      }
    }
  }
</script>
{{/if}}

{{#if style}}
<style lang="less" scoped>

</style>
{{/if}}
